import numpy as np  
import pandas as pd  
import tensorflow as tf  
from sklearn.model_selection import train_test_split  
from sklearn.preprocessing import StandardScaler  
  
# 已经准备好带钢产品的规格数据、工艺参数和硬度数据  
X = pd.read_csv('data.csv', usecols=[2, 6, 7, 9])  # 选取四个特征值  
y = pd.read_csv('data.csv', usecols=[12])         # 硬度数据  
  
# 数据预处理：标准化特征值  
scaler = StandardScaler()  
X_scaled = scaler.fit_transform(X)  
  
# 划分数据集为训练集和测试集  
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)  
  
# 使用最优的超参数来创建和编译模型  
optimal_neurons_1 = int(round(195.96664296575474))  
optimal_neurons_2 = int(round(166.0995004601362))  
optimal_neurons_3 = int(round(66.94817545910578))  
optimal_dropout_rate = 0.18727005942368125  
optimal_learning_rate = 0.00951207163345817  
  
model = tf.keras.Sequential([  
    tf.keras.layers.Dense(optimal_neurons_1, activation='relu', input_shape=(4,)),  
    tf.keras.layers.Dropout(optimal_dropout_rate),  
    tf.keras.layers.Dense(optimal_neurons_2, activation='relu'),  
    tf.keras.layers.Dense(optimal_neurons_3, activation='relu'),  
    tf.keras.layers.Dense(1)  
])  
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=optimal_learning_rate), loss='mae')  
  
# 训练模型  
model.fit(X_train, y_train, epochs=200, batch_size=32, validation_data=(X_test, y_test))  
  
# 评估模型性能  
loss = model.evaluate(X_test, y_test)  
print("模型在测试集上的损失（MAE）:", loss)
#贝叶斯优化后的超参数

import matplotlib.pyplot as plt  
  
# 使用训练好的模型进行预测  
y_pred = model.predict(X_test)  
  
# 绘制对比图  
plt.figure(figsize=(10, 6))  
plt.scatter(y_test, y_pred, color='blue', label='Predicted vs Actual')  
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'k--', lw=4, label='Perfect fit')  
plt.xlabel('Actual Values')  
plt.ylabel('Predicted Values')  
plt.title('Comparison of Predicted and Actual Values')  
plt.legend()  
plt.show()

